﻿using Infrastructure.FileOperate;
using Infrastructure.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;

namespace VideoNet.Common
{
    public class WWebClientHelper
    {
        //public static string BaseApi = "http://www.hyzschina.com";
        public static string BaseApi = ConfigurationManager.AppSettings["Host"].ToString();

        public static string LoginApiString = BaseApi + "/api/mobile/MobileLogin";
        public static string SynsApiString = BaseApi + "/api/mobile/SynsUserP";
        public static string RecentRecordApiString = BaseApi + "/api/mobile/GetRecentRecord8";
        public static string SynsSuccessApiString = BaseApi + "/api/mobile/DeleteSynsUser";
        public static string SaveAccessRecordApiString = BaseApi + "/api/mobile/SaveAccessRecord";
        public static string SaveBatchAccessRecordApiString = BaseApi + "/api/mobile/SaveBatchAccessRecord";
        public static string SaveSaveSyncErrorApiString = BaseApi + "/api/mobile/SaveSyncError";

        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="posturl">The posturl.</param>
        /// <param name="postData">The post data.</param>
        /// <returns>System.String.</returns>
        public static T HttpPost<T>(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
            byte[] data = Encoding.UTF8.GetBytes(postData);
            T obj = default(T);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/json";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                // return DataContractJsonDeserialize<T>(content);

                return content.ToObject<T>();
            }
            catch (Exception ex)
            {
                string error = ex.Message;
                FileHelper.WriteFile("D:/1.txt",ex.Message);
                return obj;
            }
        }



        #region 对象转换为Json
        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetJson<T>(T obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);
                string szJson = Encoding.UTF8.GetString(stream.ToArray());
                return szJson;
            }
        }
        #endregion


        /// <summary>
        /// json字符串转换成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json">要转换成对象的json字符串</param>
        /// <returns></returns>
        static T DataContractJsonDeserialize<T>(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T obj = default(T);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                obj = (T)serializer.ReadObject(ms);
                ms.Close();
            }
            return obj;
        }
    }
}
